import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { Form, Balloon, Button, Checkbox, Tag, Field, Switch } from '@teamix/ui';
import { Section, ButtonIcon } from '@alife/devops-ui';
// import MemberTrigger from 'components/memberTrigger';
import ListLoading from 'atComponents/ListLoading';
import track, { enterPage, Perf } from 'utils/track';
import docs from 'utils/docs';
import { Link } from 'utils/router';
import { getFeature } from 'utils/features';
import * as actions from '../actions/index';
import GuaranteeModal from './guaranteeModal';
import intl from '../../../../../../../../../locale';

const { pathResource } = window.FORCE;
const FormItem = Form.Item;

const mrSettingData = [
  {
    default: false,
    key: 'no-fast-forward',
    title: 'Merge',
    desc: intl.get({
      id: 'code-assets.settingsMergerequests.containers.root.AlwaysCreateAMergeNode',
      defaultMessage: '总是创建一个合并节点，记录合并信息',
    }),
  },

  {
    default: false,
    key: 'squash',
    title: intl.get({
      id: 'code-assets.settingsMergerequests.containers.root.MergeSquash',
      defaultMessage: 'Merge（squash）',
    }),
    desc: intl.get({
      id: 'code-assets.settingsMergerequests.containers.root.MergeAndCompressOneOr',
      defaultMessage: '将一个或多个提交合并压缩合并为目标分支上的一个提交',
    }),
  },

  {
    default: false,
    key: 'rebase',
    title: 'Rebase',
    desc: intl.get({
      id: 'code-assets.settingsMergerequests.containers.root.SubmitReviewBranchesOneBy',
      defaultMessage: '将评审分支提交逐一变基到目标分支',
    }),
  },

  {
    default: false,
    key: 'ff-only',
    title: intl.get({
      id: 'code-assets.settingsMergerequests.containers.root.MergeFastForwardOnly',
      defaultMessage: 'Merge（fast-forward-only）',
    }),
    desc: intl.get({
      id: 'code-assets.settingsMergerequests.containers.root.UseFastForwardOnlyTo',
      defaultMessage:
        '使用 fast-forward-only 方式合并，不创建合并节点。当目标分支上有提交，不能使用 fast-forward 时，默认合并类型为合并（创建合并节点）',
    }),
  },
];

const switchAction = {
  is_enable_smart_code_review: {
    name: 'is_enable_smart_code_review',
    task_name: intl.get({
      id: 'code-assets.settingsMergerequests.containers.root.IntelligentReview',
      defaultMessage: '智能评审',
    }),
    on: 'turn_on_smart_code_review',
    off: 'turn_off_smart_code_review',
  },
};

class Root extends Component {
  constructor(props) {
    super(props);
    this.field = new Field(this, {
      onChange: () => {
        this.setState({ isChanged: true });
      },
    });

    this.state = {
      isChanged: false,
      submitting: false,
      isModalOpen: false,
      modalData: {},
    };

    // 初始化mrSettingData
    mrSettingData.forEach((item) => {
      item.default = false;
    });
  }

  componentDidMount() {
    const fullName = pathResource.fullName.split('/')[1]
      ? pathResource.fullName.split('/')[1].trim()
      : '';
    document.title = intl.get(
      {
        id: 'code-assets.settingsMergerequests.containers.root.MergeRequestSettingsFullnameCloud',
        defaultMessage: '合并请求设置 · {fullName} · 云效 Codeup',
      },
      { fullName },
    );
    this.props.getMergeRequest();
    enterPage('Repo-Settings-MRs', {
      sendPerf: false,
    });
  }

  componentWillUnmount() {
    this.props.resetState();
  }

  onEventChane = (selectedItems) => {
    this.field.setValue('merge_types', selectedItems);
  };

  onSwitchChange = (key, value) => {
    this.props.onFormSave({ [switchAction[key].name]: value });
    if (value) {
      track({
        action: switchAction[key].on,
        page: 'Repo-Settings-MRs',
        type: '',
        control: '',
      });
    } else {
      track({
        action: switchAction[key].off,
        page: 'Repo-Settings-MRs',
        type: '',
        control: '',
      });
    }
  };

  modalOkFn = () => {
    const { key, value } = this.state.modalData;
    this.onSwitchChange(key, value);
    this.setState({
      isModalOpen: false,
    });
  };

  onMemberChange = (value) => {
    const { mergeRequestData } = this.props;
    mergeRequestData.default_subscribers = value;
    this.props.getFormData(mergeRequestData);
    this.field.setValue(
      'default_subscribers',
      value.map((item) => item._userId),
    );

    this.state.isChanged = true;
  };

  handleSave = () => {
    if (this.state.submitting) return;
    this.setState({ submitting: true });
    this.field.validate((errors) => {
      if (!errors) {
        const formData = this.field.getValues();
        this.props.onFormSave(formData, () => {
          this.setState({ submitting: false });
        });
      }
    });
    this.state.isChanged = false;
  };

  onDefaultClick = (value) => {
    mrSettingData.forEach((item) => {
      if (item.key === value) {
        item.default = true;
      } else {
        item.default = false;
      }
    });
    const { mergeRequestData } = this.props;
    const formData = this.field.getValues();
    let mergeDefaultType;
    if (formData.merge_types.indexOf(value) > -1) {
      const defaultType = formData.merge_types.splice(formData.merge_types.indexOf(value), 1);

      mergeDefaultType = [...defaultType, ...formData.merge_types];
    } else {
      mergeDefaultType = [...value.split(), ...formData.merge_types];
    }
    mergeRequestData.merge_types = mergeDefaultType;
    this.props.getFormData(mergeRequestData);
    this.field.setValue('merge_types', mergeDefaultType);
    this.state.isChanged = true;
  };

  render() {
    const { field } = this;
    const { init } = field;
    const { mergeRequestData } = this.props;
    // const default_subscribers = mergeRequestData
    //   ? mergeRequestData.default_subscribers
    //   : [];
    const defaultMrType = mergeRequestData ? mergeRequestData.merge_types[0] : '';
    const currentSwitchStateTS = mergeRequestData
      ? mergeRequestData.is_enable_smart_code_review
      : false;
    const mrIndex = mrSettingData.findIndex((item) => {
      if (item.key === defaultMrType) {
        item.default = true;
      }
      return item.key === defaultMrType;
    });
    const { isModalOpen, modalData, isChanged } = this.state;
    const mrSplice = mrSettingData.splice(mrIndex, 1)[0];
    // const taskName = '评审耗时智能预估';
    mrSettingData.unshift(mrSplice);
    return (
      <>
        {this.props.loading ? (
          <ListLoading />
        ) : (
          <>
            {mergeRequestData ? (
              <div className="setting-card-body mr-settings-form">
                <Perf page="Repo-Settings-MRs" />
                <Section
                  title={intl.get({
                    id: 'code-assets.settingsMergerequests.containers.root.ReviewAndMergeRules',
                    defaultMessage: '评审合并规则',
                  })}
                  description={
                    <>
                      {intl.get({
                        id: 'code-assets.settingsMergerequests.containers.root.ReviewRulesAndPermissionSettings',
                        defaultMessage:
                          '合并操作的评审规则、权限设置：如通过评审的人数指标、允许推送与合并的角色控制、自动化检测卡点等。',
                      })}
                      <br />
                      {intl.get({
                        id: 'code-assets.settingsMergerequests.containers.root.PleaseGo',
                        defaultMessage: '请前往「',
                      })}

                      <Link
                        to={`/${pathResource.fullPath}/settings/branches`}
                        style={{ color: '#1B9AEE' }}
                        onClick={() => {
                          const dom = document.querySelector('.project-setting-nav');
                          if (dom) {
                            dom.getElementsByTagName('li')[1].click();
                          }
                        }}
                      >
                        {intl.get({
                          id: 'code-assets.settingsMergerequests.containers.root.BranchSettings',
                          defaultMessage: '分支设置',
                        })}
                      </Link>
                      {intl.get({
                        id: 'code-assets.settingsMergerequests.containers.root.SetMergeRulesByProtecting',
                        defaultMessage: '」通过保护分支设置合并规则',
                      })}
                    </>
                  }
                >
                  <div />
                </Section>
                {getFeature('project.setting.merge_requests.smart_review') && (
                <Section
                  title={
                    <>
                      {intl.get({
                        id: 'code-assets.settingsMergerequests.containers.root.IntelligentReview',
                        defaultMessage: '智能评审',
                      })}
                      <Tag type="primary">NEW</Tag>
                    </>
                  }
                  description={
                    <>
                      {intl.get({
                        id: 'code-assets.settingsMergerequests.containers.root.TheIntelligentAiFeatureAllows',
                        defaultMessage:
                          '智能 AI 功能串联评审流程，助你提升评审体验，守护代码质量。',
                      })}

                      <a href={docs('estimatedReviewTime')} target="_blank" rel="noreferrer">
                        <font color="#1B9AEE">
                          {intl.get({
                            id: 'code-assets.settingsMergerequests.containers.root.LearnMore',
                            defaultMessage: '了解更多',
                          })}
                        </font>
                      </a>
                    </>
                  }
                  operation={
                    <Switch
                      className="timeestimate-switch"
                      name="is_enable_smart_code_review"
                      checked={currentSwitchStateTS}
                      onChange={(value) => {
                        // 选中需要弹窗
                        if (!value) {
                          this.onSwitchChange('is_enable_smart_code_review', value);
                          this.props.toogleService({
                            service: 'smart_code_review_service',
                            authorized: value,
                          });
                        } else {
                          this.setState({
                            isModalOpen: true,
                            modalData: {
                              service_name: 'smart_code_review_service',
                              key: 'is_enable_smart_code_review',
                              value,
                            },
                          });
                        }
                      }}
                    />
                  }
                />)}
                <Section
                  title={
                    <>
                      {intl.get({
                        id: 'code-assets.settingsMergerequests.containers.root.MergeTypeControl',
                        defaultMessage: '合并类型控制',
                      })}

                      <Balloon
                        closable={false}
                        trigger={
                          <ButtonIcon
                            name="question-line"
                            style={{ marginLeft: 4, display: 'inline-block' }}
                          />
                        }
                        popupStyle={{
                          maxWidth: 'unset',
                        }}
                        align="t"
                      >
                        {intl.get({
                          id: 'code-assets.settingsMergerequests.containers.root.SelectTheMergeTypeSupported',
                          defaultMessage: '选择合并请求中支持的合并类型，',
                        })}
                        <a href={docs('mergeRequestSettings')} target="_blank" rel="noreferrer">
                          {intl.get({
                            id: 'code-assets.settingsMergerequests.containers.root.ViewMergeMethods',
                            defaultMessage: '查看合并方式说明',
                          })}
                        </a>
                        。
                      </Balloon>
                    </>
                  }
                >
                  <>
                    <Checkbox.Group
                      itemDirection="hoz"
                      onChange={this.onEventChane}
                      {...init('merge_types', {
                        initValue: mergeRequestData.merge_types,
                      })}
                      style={{ display: 'block', height: 178 }}
                    >
                      {mrSettingData.map((item) => (
                        <div className="mr-settings-type">
                          {item.default === true ? (
                            <Checkbox id={item.key} value={item.key} disabled>
                              {item.title}
                            </Checkbox>
                          ) : (
                            <Checkbox id={item.key} value={item.key}>
                              {item.title}
                            </Checkbox>
                          )}

                          <span className="mr-settings-type-desc">
                            {item.key === 'ff-only' ? (
                              <Balloon.Tooltip trigger={item.desc} align="bl">
                                {item.desc}
                              </Balloon.Tooltip>
                            ) : (
                              item.desc
                            )}
                          </span>
                          <span className="mr-settings-type-btn">
                            {item.default === true ? (
                              <Tag size="medium">
                                {intl.get({
                                  id: 'code-assets.settingsMergerequests.containers.root.DefaultType',
                                  defaultMessage: '默认类型',
                                })}
                              </Tag>
                            ) : (
                              <Button
                                type="normal"
                                text
                                style={{ margin: '7px 8px 0px 0px' }}
                                onClick={() => this.onDefaultClick(item.key)}
                              >
                                {intl.get({
                                  id: 'code-assets.settingsMergerequests.containers.root.SetAsDefault',
                                  defaultMessage: '设为默认',
                                })}
                              </Button>
                            )}
                          </span>
                        </div>
                      ))}
                    </Checkbox.Group>
                  </>
                </Section>
                {isChanged ? (
                  <FormItem label=" " className="no-mr-b project-setting-mr-btn">
                    <Button
                      type="primary"
                      loading={this.state.submitting}
                      onClick={this.handleSave}
                    >
                      {intl.get({
                        id: 'code-assets.settingsMergerequests.containers.root.Save',
                        defaultMessage: '保存',
                      })}
                    </Button>
                  </FormItem>
                ) : null}
              </div>
            ) : null}
          </>
        )}

        {isModalOpen && (
          <GuaranteeModal
            isModalOpen={isModalOpen}
            taskName={switchAction[modalData.key].task_name}
            taskKey={modalData.key}
            serviceName={modalData.service_name}
            toogleService={this.props.toogleService}
            okFn={this.modalOkFn}
            closeFn={() => {
              this.setState({
                isModalOpen: false,
              });
            }}
          />
        )}
      </>
    );
  }
}

export default connect(
  (state) => state.project.projectSettings.settingsMergerequests,
  (dispatch) => bindActionCreators(actions, dispatch),
)(Root);
